<template>
  <div style="display:flex;flex-direction: row">
    <user_left/>

    <div class="main-container">

      <el-dialog title="请去掉口罩看摄像头" :visible.sync="dialogTableVisible"  v-loading="loading2"
                 element-loading-text="拼命识别中"
                 element-loading-spinner="el-icon-loading"
                 element-loading-background="rgba(0, 0, 0, 0.3)"
                 :data="tableData"
                 style="width: 100%" >
        <canvas ref="canvas" v-show="false" width="640"  height="480"></canvas>
        <video ref="video" width="640" height="480" autoplay></video>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取 消</el-button>
          <el-button type="primary" @click="photograph">确 定</el-button>
        </div>
      </el-dialog>

      <!--      上方加入筛选框和搜索栏，筛选框位于左侧，可筛选报修处理状态，搜索框位于右侧，绑定searchFixLog方法-->
      <el-row style="margin-top: 10px; margin-bottom: 10px" :gutter="10">

          <el-col :span="1">姓名:</el-col>
          <el-col :span="3">
            <el-input v-model="username" placeholder="请输入姓名" @change="toFilterUsers"></el-input>
          </el-col>

        <el-col :span="2">
          <el-button  type="primary" @click="callCamera(0)">外出登记</el-button>
        </el-col>
        <el-col :span="2">
          <el-button  type="primary" @click="callCamera(1)">归来登记</el-button>
        </el-col>



      </el-row>
      <el-table
          :data="userFaceList"
          style="width: 100%; border-radius: 10px"
          stripe
          border
          height="90vh"
          header-cell-class-name="table-header"
          v-loading="loading"
      >
        <el-table-column
            prop="userName"
            label="打卡人"
        ></el-table-column>

        <el-table-column
            prop="state"
            label="状态">
          <template slot-scope="scope">
            <el-tag >{{ scope.row.state ===0 ? "外出" : "归来"}}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
            prop="image"
            label="打卡图片">

          <template slot-scope="scope">
            <el-image
                style="width: 30px; height: 30px"
                :src="scope.row.image"
                :fit="fit"></el-image>
          </template>

        </el-table-column>
        <el-table-column
            prop="createTime"
            label="打卡时间">

        </el-table-column>

      </el-table>
    </div>



  </div>



</template>
<script>
import user_left from "@/components/user_left.vue";
import {Notification} from "element-ui";
import {faceSearch,faceList} from "@/api/user_api";

export default {
  components: {
    user_left
  },
  data() {
    return {
      image: "",
      username:"",
      loading2: false,
      state: 0,
      dialogTableVisible: false,
      userFaceList: [],
      user: {userId: parseInt(localStorage.getItem("id"))}
    };
  },
  created() {
    this.faceList();
  },
  methods: {
    faceList(){
      const param = {
        userId: this.user.userId
      };
      faceList(param).then(response => {
        this.loading2 = false;
        if (response.data.code === "SUCCESS") {
          this.userFaceList = response.data.data
          this.userFaceList = this.userFaceList.filter(item =>  this.user.userId === item.userId);
          console.log(response.data.data)
        } else if (response.data.code === "ERROR") {
          Notification({
            title: "获取打卡列表失败",
            type: "error"
          });
        } else if (response.data.code === "TIMEOUT") {
          Notification({
            title: "登录信息已过期，请重新登录",
            type: "warning"
          });
        }
      });
    },
    closeAlert(){
      this.dialogTableVisible = false;
      this.closeCamera();
    },
    // 调用摄像头
    callCamera(state) {
      this.dialogTableVisible = true;
      this.state = state;
      navigator.mediaDevices
          .getUserMedia({
            audio: true,//调用音频
            video: true, //说明请求的媒体类型。调用视频
          })
          .then((success) => {
            // 摄像头开启成功
            this.$refs["video"].srcObject = success;
            // 实时拍照效果
            this.$refs["video"].play();
          })
          .catch((error) => {
            //用户拒绝
            console.error("摄像头开启失败，请检查摄像头是否可用！");
          });
    },
    toFilterUsers() {
      if(this.username !== ""){
        this.userFaceList = this.userFaceList.filter(item => item.userName.includes(this.username) && this.user.userId === item.userId);
      }else{
        this.faceList();
      }
    },
    // 拍照
    photograph() {

      let ctx = this.$refs["canvas"].getContext("2d");
      // 把当前视频帧内容渲染到canvas上
      ctx.drawImage(this.$refs["video"], 0, 0, 640, 480);
      //canvas图片 转base64格式、图片格式转换、图片质量压缩
      //语法 canvas.toDataURL(type, encoderOptions); 设置转换的图片格式、图片质量压缩
      let imgBase64 = this.$refs["canvas"].toDataURL("image/jpeg", 0.7);
      let str = imgBase64.replace("data:image/jpeg;base64,", "");
      this.image = str;
      let strLength = str.length;
      //let fileLength = parseInt(strLength - (strLength / 8) * 2); //
      //let size = (fileLength / 1024).toFixed(2);// 由字节转换为KB 判断大小
      //console.log(size); //图片大小
      this.closeCamera();
      this.loading2 = true;
      this.faceSearch();
    },
    // 关闭摄像头
    closeCamera() {
      if (!this.$refs["video"].srcObject) {
        return;
      }
      //MediaStream 接口的getTracks() 方法会返回一个包含媒体流中所有媒体对象
      let stream = this.$refs["video"].srcObject;
      let tracks = stream.getTracks();
      tracks.forEach((track) => {
        track.stop();
      });
      this.$refs["video"].srcObject = null;
    },
    faceSearch() {
      const param = {
        userId: this.user.userId,
        image : this.image,
        state : this.state
      };
      faceSearch(param).then(response => {
        this.loading2 = false;
        if (response.data.code === "SUCCESS") {
          if(response.data.data.error_code === 222202){
            Notification({
              title: "打卡失败:未检测到人脸",
              type: "error"
            });
          }if(response.data.data.error_code  === "SDK108"){
            Notification({
              title: "打卡失败:网络超时",
              type: "error"
            });
          }if(response.data.data.error_code  === 0){
            this.closeAlert();
            this.faceList();
            Notification({
              title: "打卡成功",
              type: "error"
            });
          }
        } else if (response.data.code === "ERROR") {
          Notification({
            title: "打卡失败",
            type: "error"
          });
        } else if (response.data.code === "TIMEOUT") {
          Notification({
            title: "登录信息已过期，请重新登录",
            type: "warning"
          });
        }
      });
    },
  }
}

</script>

<style scoped>
.main-container {
  width: 70%;
  margin: 0 auto;
  align-content: center;
}

</style>